package com.labManage.shiro;

import com.labManage.dao.PermitionDao;
import com.labManage.dao.UserDao;
import com.labManage.entity.Permition;
import com.labManage.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class CustomRealm extends AuthorizingRealm {

    private UserDao userDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Autowired
    PermitionDao permitionDao;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("权限管理");
        User user = (User) principalCollection.getPrimaryPrincipal();

        List<Permition> list = permitionDao.getPermitonsByUserId(user.getId());
        Set<String> set = new HashSet<>();
        for (Permition per : list) {
            set.add(per.getPermitionCode());
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(set);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("登录认证");
        String userNo = (String) authenticationToken.getPrincipal();
        User user = new User();
        user.setUserNo(userNo);
        List<User> users = userDao.selectUser(user);
        if(users==null){
            return null;
        }
        return new SimpleAuthenticationInfo(users.get(0),users.get(0).getPassword(), ByteSource.Util.bytes("123"),"hp");
    }
}
